import './index.less';
import * as echarts from 'echarts';
import { option } from "./option.ts";
import { useEffect, useRef } from "react";
import useAppState from "../../store";

const RadarGraph = () => {
    // 使用 useRef 持久化保存 ECharts 实例
    const chartRef = useRef<echarts.ECharts | null>(null);
    const chartContainerRef = useRef<HTMLDivElement | null>(null);
    const {graphData,tensileStrength,yieldStrength, getState} = useAppState();

    useEffect(() => {
        // 初始化逻辑（仅执行一次）
        if (!chartRef.current && chartContainerRef.current) {
            // 1. 初始化图表
            chartRef.current = echarts.init(chartContainerRef.current);

            // 2. 添加窗口自适应监听
            const resizeHandler = () => chartRef.current?.resize();
            window.addEventListener('resize', resizeHandler);

            // 3. 组件卸载时的清理函数
            return () => {
                window.removeEventListener('resize', resizeHandler);
                chartRef.current?.dispose();
                chartRef.current = null;
            };
        }
    }, []);

    // 配置更新逻辑（testData 变化时触发）
    useEffect(() => {
        if(graphData.nodes.length===0) return;
        if (chartRef.current && option) {
            option.radar.indicator=Object.keys(tensileStrength).map(item=>({name:item,max:1}))
            const tensileValues = Object.values(tensileStrength);
            tensileValues[2]=parseFloat((1-tensileValues[2]/2).toFixed(4));
            const yieldValues = Object.values(yieldStrength);
            yieldValues[2]=parseFloat((1-yieldValues[2]/2).toFixed(4));
            option.series[0].data[0].value=tensileValues;
            // debugger;
            option.series[0].data[1].value=yieldValues;
            // 使用 setOption 更新配置而非重新初始化
            chartRef.current.setOption(option);
        }
    }, [graphData]);

    return (
        <div
            id="RadarGraph"
            ref={(el) => {
                chartContainerRef.current = el;
            }}
        />
    );
};

export default RadarGraph;
